package com.andy.eqm.server.socket;

import java.net.InetSocketAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.andy.eqm.server.dao.DbBatch;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

public class GameServer {
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	private final EventLoopGroup bossGroup = new NioEventLoopGroup();
	private final EventLoopGroup workGroup = new NioEventLoopGroup();
	private Channel channel;
	
	private static int status = 0; // 服务器状态，0-启动中，1-启动完成，-1-关闭中
	
	public ChannelFuture start(InetSocketAddress address) {
		ServerBootstrap bootstrap = new ServerBootstrap();
		bootstrap.group(bossGroup, workGroup)
				.channel(NioServerSocketChannel.class)
				.childHandler(new GameServerInitializer())
				.option(ChannelOption.SO_BACKLOG, 128)
				.childOption(ChannelOption.SO_KEEPALIVE, true);
		
		ChannelFuture future = bootstrap.bind(address).syncUninterruptibly();
		channel = future.channel();
		future.addListener(new GenericFutureListener<Future<? super Void>>() {
			@Override
			public void operationComplete(Future<? super Void> paramF) throws Exception {
				// 启动完成，开始接客
		    	ok();
				System.out.println("服务器启动完成");
			}
			
		});
		future.channel().closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {
			@Override
			public void operationComplete(Future<? super Void> paramF) throws Exception {
				System.out.println("服务器已关闭");
				DbBatch.stopBatch();
				System.out.println("数据落地完成");
				if(channel == null){
					// 说明手动关闭
					System.exit(0);
				}
			}
			
		});
		return future;
	}
	
	public void destroy() {
		status = -1;
		if(channel != null) {
			channel.close();
			channel = null;
		}
		
	}

	public static void ok() {
		status = 1;
	}
	public static boolean isOk(){
		return status == 1;
	}
	
}